<?php

namespace App\Models;

use Identicon\Identicon;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;

class User extends Authenticatable
{
    use Notifiable, MustVerifyEmail;

    protected $fillable = [
        'name',
        'nickname',
        'email',
        'sex',
        'province',
        'city',
        'country',
        'avatar',
        'provider',
        'language',
        'email_verified_at',
        'mobile',
        'qq',
        'birthday'
    ];

    protected $hidden = [
        'openid',
        'access_token',
        'unionid',
        'password'
    ];

    const PROVIDER_WECHAT = 'WeChat'; // 微信授权用户
    const PROVIDER_LOCAL = 'local'; // 本地自动分配的用户
    const PROVIDER_ROBOT = 'robot'; // 本地自动生成的机器人

    public static $providerMaps = [
        self::PROVIDER_LOCAL => '游客',
        self::PROVIDER_WECHAT => '微信用户',
        self::PROVIDER_ROBOT => '机器人',
    ];

    const SEX_NAN = 1; // 男性
    const SEX_NV = 2; // 女性

    public static $sexMaps = [
        self::SEX_NAN => '男',
        self::SEX_NV => '女',
    ];

    protected $dates = [
        'email_verified_at',
        'birthday'
    ];


    protected static function boot()
    {
        parent::boot();
        static::creating(
            function (User $user) {
                if (is_null($user->nickname)) {
                    $user->nickname = static::randNickName();
                    $user->name = $user->name ?: $user->nickname;
                }
                if (is_null($user->avatar)) {
                    $identicon = new Identicon();
                    $user->avatar = $identicon->getImageDataUri($user->nickname, 25);
                }
            }
        );
    }

    // 关联地址
    public function addresses()
    {
        return $this->hasMany(UserAddress::class);
    }

    // 关联收藏的商品单品
    public function favoriteProducts()
    {
        return $this->belongsToMany(Product::class, 'user_favorite_products')
            ->withTimestamps()
            ->orderBy('created_at', 'desc');
    }

    // 关联购物车
    public function cartItems()
    {
        return $this->hasMany(CartItem::class);
    }
    
    // 关联领取的优惠券
    public function couponCodes()
    {
        return $this->belongsToMany(CouponCode::class, 'user_coupon_codes')
            ->withTimestamps()
            ->orderBy('created_at', 'desc');
    }

    // 关联订单列表
    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    // 远程一对多关联订单项
    public function orderItems()
    {
        return $this->hasManyThrough(OrderItem::class, Order::class);
    }

    // 随机生成一个昵称
    public static function randNickName()
    {
        $pre = 'user_';
        do {
            $str = strtoupper(Str::random(11));
            $nickname = $pre.$str;
        } while (self::query()->where('nickname', $nickname)->exists());

        return $nickname;
    }
}
